package com.tem.system.utils;

import com.api.manage.pojo.system.SysBranchOfficeResources;
import com.api.manage.redis.RedisCacheUtil;
import com.tem.common.core.domain.SysRoleDataScope;
import com.tem.system.service.ISysBranchOfficeService;
import com.tem.system.service.SysUserService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
@Lazy
public class LocalRedisUtils {
    @Autowired
    private RedisCacheUtil redisCacheUtil;
    @Autowired
    private ISysBranchOfficeService sysBranchOfficeService;
    @Autowired
    private SysUserService sysUserService;
    @ApiOperation(value = "获取分公司、分店资源缓存")
    public SysBranchOfficeResources getSysBranchOfficeResources(Long sysBranchOfficeId){
        SysBranchOfficeResources resources = (SysBranchOfficeResources)redisCacheUtil.getObject(RedisCacheUtil.SysBranchOfficeResources , sysBranchOfficeId);
        if(resources!=null) return resources;
        return setSysBranchOfficeResources(sysBranchOfficeId);
    }
    @ApiOperation(value = "添加分公司、分店资源缓存")
    public SysBranchOfficeResources setSysBranchOfficeResources(Long sysBranchOfficeId){
        SysBranchOfficeResources resources = sysBranchOfficeService.getAllResources(sysBranchOfficeId);
        redisCacheUtil.setObject(RedisCacheUtil.SysBranchOfficeResources,sysBranchOfficeId,resources);
        return resources;
    }
    @Async("sysTaskExecutor")
    @ApiOperation(value = "异步添加分公司、分店资源缓存")
    public void setSysBranchOfficeResourcesThread(Long sysBranchOfficeId){
        SysBranchOfficeResources resources = (SysBranchOfficeResources)redisCacheUtil.getObject(RedisCacheUtil.SysBranchOfficeResources , sysBranchOfficeId);
        if(resources!=null) return ;
        resources = sysBranchOfficeService.getAllResources(sysBranchOfficeId);
        redisCacheUtil.setObject(RedisCacheUtil.SysBranchOfficeResources,sysBranchOfficeId,resources);
    }

    @Async("sysTaskExecutor")
    @ApiOperation(value = "异步设置用户所有权限资源缓存")
    public void setAllSysRoleDataScope(Long sysBranchOfficeId){
//        List<SysRoleDataScope> resources = (List<SysRoleDataScope>)redisCacheUtil.getObject(RedisCacheUtil.SysRoleDataScopeAll , sysBranchOfficeId);
//        if(resources!=null) return ;
        List<SysRoleDataScope> resources = sysUserService.getAllSysRoleDataScope(sysBranchOfficeId);
        if(resources==null || resources.size()<1) return ;
        redisCacheUtil.setObject(RedisCacheUtil.SysRoleDataScopeAll,sysBranchOfficeId,resources);
    }

}